package com.aiyige.page.globalsearch;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.ApiManager;
import com.aiyige.model.Page;
import com.aiyige.model.User;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.globalsearch.adapter.SearchAdapter;
import com.aiyige.page.globalsearch.event.EventGlobalSearch;
import com.aiyige.page.globalsearch.model.SearchData;
import com.aiyige.page.globalsearch.util.SearchPageInterface;
import com.aiyige.page.globalsearch.util.SearchUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.widget.AutoRefreshCommonDataView;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.fastjson.JSON;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class SearchDetailPage extends BaseFragment implements SearchPageInterface, CommonDataView.RetrofitStub, AutoRefreshCommonDataView.Callback {
    int pageType;
    String pageTitle;
    String searchWord;
    @BindView(R.id.cdv)
    AutoRefreshCommonDataView cdv;
    Unbinder unbinder;
    SearchAdapter searchAdapter;
    volatile boolean shouldRefresh = false;
    View countHeader;
    TextView countTv;

    public SearchDetailPage() {
        setAutoRegisterEventBus(true);
    }

    public static BaseFragment newInstance(int pageType) {
        SearchDetailPage searchDetailPage = new SearchDetailPage();
        searchDetailPage.setPageTitle(SearchUtil.covertPageTypeToPageTitle(pageType));
        searchDetailPage.setPageType(pageType);
        return searchDetailPage;
    }

    public int getPageType() {
        return pageType;
    }

    public void setPageType(int pageType) {
        this.pageType = pageType;
    }

    public String getPageTitle() {
        return pageTitle;
    }

    public void setPageTitle(String pageTitle) {
        this.pageTitle = pageTitle;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.page_search_detail, container, false);
        unbinder = ButterKnife.bind(this, view);
        searchAdapter = new SearchAdapter(getActivity());
        cdv.config(searchAdapter, this);
        cdv.setCallback(this);
        initHeader(inflater);
        return view;
    }

    public void initHeader(LayoutInflater inflater) {
        countHeader = inflater.inflate(R.layout.global_search_count_header, (ViewGroup) cdv.getRecyclerView().getParent(), false);
        countTv = countHeader.findViewById(R.id.countTv);
        searchAdapter.addHeaderView(countHeader);
    }

    @Override
    public String pageTitle() {
        return pageTitle;
    }

    @Override
    public int pageType() {
        return pageType;
    }

    @Override
    public void searchWord(String searchWord) {
        this.searchWord = searchWord;
    }

    @Override
    protected void initData() {
        shouldRefresh = true;
        cdv.doRefreshRequest();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        shouldRefresh = false;
        Call<ResponseBody> call;
        switch (pageType) {
            case SearchUtil.PAGE_TYPE_SEARCH_USER:
                call = ApiManager.getService().searchUser(searchWord, currentPage, 20);
                break;
            case SearchUtil.PAGE_TYPE_SEARCH_INFO:
                call = ApiManager.getService().allSearchZone(searchWord, Moment.SUBJECT_ARTICLE, currentPage, 20);
                break;
            case SearchUtil.PAGE_TYPE_SEARCH_PHOTO:
                call = ApiManager.getService().allSearchZone(searchWord, Moment.SUBJECT_PHOTO, currentPage, 20);
                break;
            case SearchUtil.PAGE_TYPE_SEARCH_VIDEO:
                call = ApiManager.getService().allSearchZone(searchWord, Moment.SUBJECT_VIDEO, currentPage, 20);
                break;
            case SearchUtil.PAGE_TYPE_SEARCH_SPECIAL_TOPIC:
                call = ApiManager.getService().allSearchZone(searchWord, Moment.SUBJECT_SPECIAL_TOPIC, currentPage, 20);
                break;
            case SearchUtil.PAGE_TYPE_SEARCH_LEARN_VIDEO:
                call = ApiManager.getService().allSearchZone(searchWord, Moment.SUBJECT_VIDEO_COURSE, currentPage, 20);
                break;
            case SearchUtil.PAGE_TYPE_SEARCH_MAJOR_COURSE:
                call = ApiManager.getService().allSearchZone(searchWord, Moment.SUBJECT_MAJOR_COURSE, currentPage, 20);
                break;
            default:
                call = ApiManager.getService().allSearchZone(searchWord, Moment.SUBJECT_MAJOR_COURSE, currentPage, 20);
                break;
        }
        return call;
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        switch (pageType) {
            case SearchUtil.PAGE_TYPE_SEARCH_USER:
                return handleUserResponse(respJson, resultList);
            default:
                return handleMomentResponse(respJson, resultList);
        }
    }


    public CommonDataView.HandleResult handleUserResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<User> userList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                userList.addAll(JSON.parseArray(page.getContent(), User.class));
            }
            for (User user : userList) {
                resultList.add(SearchData.parse(new User(user), searchWord));
            }
            countTv.setText(StringUtils.getString(R.string.total_result_count, StringUtils.formatNum(page.getTotalElements())));
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    public CommonDataView.HandleResult handleMomentResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }
            for (Moment moment : momentList) {
                resultList.add(SearchData.parse(new Moment(moment), searchWord));
            }
            countTv.setText(StringUtils.getString(R.string.total_result_count, StringUtils.formatNum(page.getTotalElements())));
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    @Override
    public void onClearRequestState() {
        if (shouldRefresh) {
            cdv.refresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventGlobalSearch event) {
        switch (event.getType()) {
            case EventGlobalSearch.TYPE_DO_SEARCH: {
                if (isFragmentVisible()) {
                    shouldRefresh = true;
                    cdv.refresh();
                } else {
                    cdv.showRefreshing();
                    setForceLoad(true);
                }
                break;
            }
        }
    }
}
